//封装购物车相关的Pinia方法
import {defineStore} from "pinia";
import {ref,computed} from "vue"
import {useUserstore} from "./user.js";
import {useRouter} from "vue-router";
const router = useRouter()

export const useCartStore =defineStore('cartStore',()=>{
  const userStore = useUserstore()
  const islogin = computed(() => {
    // 使用双重否定转为布尔值，再转换为数字
    return Number(!!userStore.userInfo?.token)
  })
  //定义state
  const cartList = ref([])
  //计算属性
  //总数量
  const allCount = computed(() => {
    return cartList.value.reduce((pre, item) => {
      return pre + item.count
    }, 0)
  })
  //总价
  const allPrice = computed(() => {
    return cartList.value.reduce((pre, item) => {
      return pre + item.count * item.price
    }, 0)
  })
  //全选数据
  const isAll1 = computed(() => {
    //如果购物车中有数据，判断是否全部选中,;可时刻进行监听，全中时返回true
    return cartList.value.every(item => item.selected)
  })
  //已选择数量
  const checkedCount = computed(() => {
    return cartList.value.filter(item => item.selected)
      .reduce((pre, item) => {
      return pre + item.count
    }, 0)
  })
  //选择商品的价钱合计
  const checkedPrice = computed(() => {
    return cartList.value.filter(item => item.selected)
      .reduce((pre, item) => {
      return pre + item.count * item.price
    }, 0)
  })
  // 新增选中商品列表计算属性
  const selectedItems = computed(() => {
    return cartList.value.filter(item => item.selected)
  })

  //定义action
  //添加数据
  const addCart = (goods)=>{
    //判断是否登录
    if (!islogin.value) {
      router.push('/login')
      return
    }
    //通过匹配传递过来的商品对象中的id，判断是否添加过
    //已添加过 count+1
    //没有添加过，直接push
    const item = cartList.value.find(item => goods.skuId === item.skuId)
    if (item) {
      item.count += goods.count
    } else {
      cartList.value.push(goods)
    }
  }
  //删除数据
  const delCart = (skuId)=>{
    const index = cartList.value.findIndex(item => skuId === item.skuId)
    cartList.value.splice(index,1)
  }
  //删除全部数据
  const delAllCart = ()=>{
    cartList.value = []
  }
  //单选数据
  const singleCheck = (skuId,selected)=>{
    //找到对应的数据，修改checked
    const item = cartList.value.find(item => skuId === item.skuId)
    item.selected = selected
  }
  //全选数据
  const isAll = (selected) => {
    cartList.value.forEach(item => item.selected = selected)
  }

  //以对象的格式return出去
  return {cartList,addCart,delCart,allCount,allPrice,singleCheck,isAll,isAll1,checkedCount,checkedPrice,selectedItems,delAllCart}
},{
  persist:true
})
